package wy.hanyufang.cn.controller;

import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;
import wy.hanyufang.cn.socket.handler.ScannerLoginSocketHandler;
import wy.hanyufang.cn.utils.CacheUtil;
import wy.hanyufang.cn.utils.QRCodeUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @author ： wyhanyufang@163.com
 * @time ： 11:06 AM 2021/9/21
 */
@RestController
@RequestMapping("/qrcode/")
public class QRCodeController {
    private static final Logger logger = LoggerFactory.getLogger(QRCodeController.class);

    //获取二维码
    @GetMapping("generator")
    public void qrCode(@RequestParam("channelId") String channelId, HttpServletRequest request,
                       HttpServletResponse response) throws Exception{
        System.out.println("生成二维码...");
        response.setContentType("image/png");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
//        QRCodeUtil.generatorLogQRCode("http://localhost/qrcode/login",
//                "/Users/apple/Documents/hanyufang/code-scanning-login/touxiang.jpeg",
//                savePath);
        QRCodeUtil.generatorQRCode("http://192.168.1.76:8080/qrcode/login?channelId=" + channelId
                ,outputStream);

        InputStream stream = new ByteArrayInputStream(outputStream.toByteArray());

        OutputStream responseStream = new BufferedOutputStream(response.getOutputStream());
        byte[] bytes = new byte[1024];
        int n;
        while ((n = stream.read(bytes)) != -1){
            responseStream.write(bytes,0,n);
        }
        responseStream.flush();
        responseStream.close();
        outputStream.close();
    }

    @GetMapping("index")
    public ModelAndView index(){
        ModelAndView index = new ModelAndView("index");
        return index;
    }

    @GetMapping("simple")
    public ModelAndView simple(){
        ModelAndView simple = new ModelAndView("html/simple");
        return simple;
    }

    @GetMapping("login")
    public void login(@RequestParam("channelId") String channelId){
        logger.info("开始扫码登录:channelId={}",channelId);

        ScannerLoginSocketHandler.sendMessage((Channel) CacheUtil.get(channelId),"loginStatus=success");
    }
}
